package com.gzu.finalwork.user.controller;

import com.gzu.finalwork.user.config.AjaxResult;
import com.gzu.finalwork.entity.user.DeliveryOrders;
import com.gzu.finalwork.entity.user.DeliveryTrack;
import com.gzu.finalwork.user.service.DeliveryOrdersService;
import com.gzu.finalwork.user.service.DeliveryTrackService;
import com.gzu.finalwork.common.utils.SensitiveOperation;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/deliveryOrders")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class DeliveryOrdersController {
    @Autowired
    private DeliveryOrdersService deliveryOrdersService;
    @Autowired
    private DeliveryTrackService trackService;


    //创建订单
    @PostMapping("/createDeliveryOrder")
    public  Object createDeliveryOrder(@RequestBody DeliveryOrders deliveryOrders, HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        deliveryOrders.setUserId(userId);
        try{
            return AjaxResult.success(deliveryOrdersService.createDeliveryOrders(deliveryOrders),"创建订单成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"创建订单失败");
        }
    }


    //根据订单号获取订单详情
    @PostMapping("/getDeliveryOrderDetail")
    public Object getDeliveryOrderDetail(Long deliveryOrderId){
        try{
            return AjaxResult.success(deliveryOrdersService.selectByDeliveryOrderId(deliveryOrderId),"获取订单详情成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单详情失败");
        }
    }

    //根据orderNumber OR senderName OR receiverName获取订单列表
    @PostMapping("/selectDeliveryOrderList")
    public Object selectDeliveryOrderList(@RequestParam String orderNumber,
                                          @RequestParam String senderName,
                                          @RequestParam String receiverName,
                                          @RequestParam(defaultValue = "1") int pageNum,
                                          @RequestParam(defaultValue = "10") int pageSize,
                                          HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            DeliveryOrders deliveryOrders = new DeliveryOrders();
            deliveryOrders.setOrderNumber(orderNumber);
            deliveryOrders.setSenderName(senderName);
            deliveryOrders.setReceiverName(receiverName);
            deliveryOrders.setUserId(userId);
            List<DeliveryOrders> deliveryOrdersList = deliveryOrdersService.selectDeliveryOrdersList(deliveryOrders,pageNum,pageSize);
            Integer total = deliveryOrdersService.selectDeliveryOrdersCountByUserId(deliveryOrders); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(1,resultData);
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    //根据订单号删除订单
    @SensitiveOperation(
        value = "用户删除订单", 
        operationType = "删除操作"
    )
    @PostMapping("/deleteDeliveryOrder")
    public Object deleteDeliveryOrder(Long deliveryOrderId){
        try{
            return deliveryOrdersService.deleteDeliveryOrder(deliveryOrderId);
        }catch (Exception e){
            return AjaxResult.error(-1,"删除订单失败");
        }
    }

    /***
     * 获取个人订单列表
     */
    //获取个人各类订单数量
    @GetMapping("/getDeliveryOrderCount")
    public Object getDeliveryOrderCount(HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            Integer tatol = deliveryOrdersService.getDeliveryOrdersCountByUserId(userId);
            Integer pending = deliveryOrdersService.getDeliveryCountByUserId(userId,1);
            Integer processing = deliveryOrdersService.getDeliveryCountByUserId(userId,2);
            Integer deliverying = deliveryOrdersService.getDeliveryCountByUserId(userId,3);
            Integer completed = deliveryOrdersService.getDeliveryCountByUserId(userId,4);
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("total",tatol);
            resultData.put("pending",pending);
            resultData.put("processing",processing);
            resultData.put("deliverying",deliverying);
            resultData.put("completed",completed);
            return AjaxResult.success("获取订单列表成功",resultData);
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    //获取个人全部订单列表
    @PostMapping("/getDeliveryOrderList")
    public Object getDeliveryOrderList(@RequestParam(defaultValue = "1") int pageNum,
                                       @RequestParam(defaultValue = "10") int pageSize,
                                       HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            List<DeliveryOrders> deliveryOrdersList = deliveryOrdersService.getDeliveryOrdersList(userId,pageNum,pageSize);
            Integer total = deliveryOrdersService.getDeliveryOrdersCountByUserId(userId); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(1,resultData);
            }
        catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    //获取订单状态分类列表,1-待发货
    @PostMapping("/getDeliveryStatusList")
    public Object getDeliveryStatusList(@RequestParam(defaultValue = "1") int pageNum,
                                        @RequestParam(defaultValue = "10") int pageSize,
                                        HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            List<DeliveryOrders> deliveryOrdersList = deliveryOrdersService.getDeliveryOrdersListByStatus(userId,pageNum,pageSize);
            Integer total = deliveryOrdersService.getDeliveryCountByUserId(userId,1); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(resultData,"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }
    //获取订单状态分类列表,2-运输中,
    @PostMapping("/getDeliveryProcessingList")
    public Object getDeliveryProcessingList(@RequestParam(defaultValue = "1") int pageNum,
                                            @RequestParam(defaultValue = "10") int pageSize,
                                            HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            List<DeliveryOrders> deliveryOrdersList = deliveryOrdersService.getDeliveryProcessingList(userId,pageNum,pageSize);
            Integer total = deliveryOrdersService.getDeliveryCountByUserId(userId,1); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(resultData,"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }
    //获取订单状态分类列表,3-待签收
    @PostMapping("/getDeliveryDeliveryingList")
    public Object getDeliveryDeliveryingList(@RequestParam(defaultValue = "1") int pageNum,
                                             @RequestParam(defaultValue = "10") int pageSize,
                                             HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            List<DeliveryOrders> deliveryOrdersList = deliveryOrdersService.getDeliveryDeliveryingList(userId,pageNum,pageSize);
            Integer total = deliveryOrdersService.getDeliveryCountByUserId(userId,1); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(resultData,"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    //获取订单状态分类列表,4-已完成
    @PostMapping("/getDeliveryCompletedList")
    public Object getDeliveryCompletedList(@RequestParam(defaultValue = "1") int pageNum,
                                           @RequestParam(defaultValue = "10") int pageSize,
                                           HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        try{
            List<DeliveryOrders> deliveryOrdersList = deliveryOrdersService.getDeliveryCompletedList(userId,pageNum,pageSize);
            Integer total = deliveryOrdersService.getDeliveryCountByUserId(userId,1); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(resultData,"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    /**
     * 给该订单增加配送员操作
     */
    //给该订单增加配送员,接单按钮
    @PostMapping("/addDeliverer")
    public Object addDeliverer(Long deliveryOrderId, HttpSession session){
        try{
            //改变订单状态
            Long delivererId = (Long) session.getAttribute("userId");
            deliveryOrdersService.addDeliverer(deliveryOrderId, delivererId);
            //改变物流跟踪记录
            DeliveryTrack.TrackRecord record = new DeliveryTrack.TrackRecord();
            record.setTimestamp(LocalDateTime.now());
            record.setStatus(2); // 已揽件
            record.setDescription("配送员已接单");
            record.setOperator("配送员ID:" + delivererId);

            trackService.addTrackRecord(deliveryOrderId, record);
            return AjaxResult.success("配送员添加成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"配送员添加失败");
        }
    }

    //改变订单状态,配送按钮
    @PostMapping("/setProcessing")
    public Object setProcessing(Long deliveryOrderId,HttpSession session){
        try{
            //改变订单状态
            Long delivererId = (Long) session.getAttribute("userId");
            deliveryOrdersService.setProcessing(deliveryOrderId);
            //改变物流跟踪记录
            DeliveryTrack.TrackRecord record = new DeliveryTrack.TrackRecord();
            record.setTimestamp(LocalDateTime.now());
            record.setStatus(4); // 派送中
            record.setDescription("开始配送");
            record.setOperator("配送员ID:" + delivererId);
            trackService.addTrackRecord(deliveryOrderId, record);
            return AjaxResult.success("订单状态修改成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"订单状态修改失败");
        }
    }

    //改变订单状态,送达按钮
    @PostMapping("/setDeliverying")
    public Object setDeliverying(Long deliveryOrderId){
        try{
            deliveryOrdersService.setDeliverying(deliveryOrderId);
            return AjaxResult.success("订单状态修改成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"订单状态修改失败");
        }
    }

    //获取所有的订单状态分类列表,1-待处理
    @PostMapping("/getPending")
    public Object getPending(){
        try{
            return AjaxResult.success(deliveryOrdersService.selectStatusPending(),"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }


    //获取所有的订单状态分类列表,2-处理中
    @PostMapping("/getProcessing")
    public Object getProcessing(HttpSession session){
        try{

            Long userId = (Long) session.getAttribute("userId");
            return AjaxResult.success(deliveryOrdersService.selectStatusProcessing(userId),"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    //获取所有的订单状态分类列表,3-配送中
    @PostMapping("/getDeliverying")
    public Object getDeliverying(HttpSession session){
        try{
            Long userId = (Long) session.getAttribute("userId");
            return AjaxResult.success(deliveryOrdersService.selectStatusDeliverying( userId),"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }

    //获取所有的订单状态分类列表,4-已完成
    @PostMapping("/getCompleted")
    public Object getCompleted( HttpSession session){
        try{
            Long userId = (Long) session.getAttribute("userId");
            return AjaxResult.success(deliveryOrdersService.selectStatusCompleted(userId),"获取订单列表成功");
        }catch (Exception e){
            return AjaxResult.error(-1,"获取订单列表失败");
        }
    }


}
